import { drizzle } from 'drizzle-orm/bun-sqlite';
import { Database } from 'bun:sqlite';
import { migrate } from 'drizzle-orm/bun-sqlite/migrator';
import * as schema from './schema';
import { runAllSeeds } from './seeds/index';

// 创建数据库连接
const sqlite = new Database('database.sqlite');
export const db = drizzle(sqlite, { schema });

/**
 * 初始化数据库
 * 运行迁移并填充初始数据
 */
export async function initDatabase() {
  try {
    console.log('🔄 Initializing database...');
    
    // 检查数据库是否已经初始化
    try {
      const result = await db.select().from(schema.products).limit(1);
      console.log('✅ Database already initialized, skipping migration');
      return true;
    } catch (error) {
      // 数据库未初始化，继续执行迁移
      console.log('📦 Database not found, running migrations...');
    }
    
    // 运行数据库迁移
    try {
      await migrate(db, { migrationsFolder: './drizzle' });
      console.log('✅ Database migrations completed');
    } catch (error) {
      console.log('⚠️ Migration error:', error);
      throw error;
    }
    
    // 填充初始数据
    console.log('🌱 开始填充种子数据...');
    await runAllSeeds();
    console.log('✅ 种子数据填充完成');
    
    return true;
  } catch (error) {
    console.error('❌ Database initialization failed:', error);
    // 不抛出错误，允许服务继续启动
    return false;
  }
}

/**
 * 关闭数据库连接
 */
export function closeDatabase() {
  try {
    sqlite.close();
    console.log('✅ Database connection closed');
  } catch (error) {
    console.error('❌ Error closing database:', error);
  }
}

// 优雅关闭处理
process.on('SIGINT', () => {
  console.log('\n🔄 Gracefully shutting down...');
  closeDatabase();
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.log('\n🔄 Gracefully shutting down...');
  closeDatabase();
  process.exit(0);
});